package com.ens.app;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.http.conn.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;

import org.apache.http.conn.ssl.X509HostnameVerifier;

import sameClasses.NetworkPacket;
import sameClasses.User;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class LoginDataActivity extends Activity {

	Bundle myState;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		super.onCreate(savedInstanceState);
		myState = savedInstanceState;
		setContentView(R.layout.login_activity);

		View continueButton = findViewById(R.id.buttonContinue);
		continueButton.setOnClickListener(new OnClickListener() {
			// http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/6378872#6378872
			@Override
			public void onClick(View v) {
				/*
				try {

					SSLContext ctx = SSLContext.getInstance("TLS");
					X509TrustManager tm = new X509TrustManager() {

						public void checkClientTrusted(X509Certificate[] xcs,
								String string) throws CertificateException {
						}

						public void checkServerTrusted(X509Certificate[] xcs,
								String string) throws CertificateException {
						}

						@Override
						public java.security.cert.X509Certificate[] getAcceptedIssuers() {
							return null;
						}

						@Override
						public void checkClientTrusted(
								java.security.cert.X509Certificate[] chain,
								String authType)
								throws java.security.cert.CertificateException {
							// TODO Auto-generated method stub

						}

						@Override
						public void checkServerTrusted(
								java.security.cert.X509Certificate[] chain,
								String authType)
								throws java.security.cert.CertificateException {
							// TODO Auto-generated method stub

						}
					};
					X509HostnameVerifier verifier = new X509HostnameVerifier() {

						@Override
						public void verify(String string, SSLSocket ssls)
								throws IOException {
						}

						@Override
						public void verify(String string, String[] strings,
								String[] strings1) throws SSLException {
						}

						@Override
						public boolean verify(String string, SSLSession ssls) {
							return true;
						}

						@Override
						public void verify(String host,
								java.security.cert.X509Certificate cert)
								throws SSLException {
							// TODO Auto-generated method stub

						}
					};
					ctx.init(null, new TrustManager[] { tm }, null);
					SSLSocketFactory factory = new MySSLSocketFactory(ctx);
					factory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
					Socket socket = new Socket(
							((EditText) findViewById(R.id.editIPorHostname))
									.getText().toString(),
							Integer.parseInt(((EditText) findViewById(R.id.editPort))
									.getText().toString()));
					SSLSocket server = (SSLSocket) factory.createSocket(
							socket,
							((EditText) findViewById(R.id.editIPorHostname))
									.getText().toString(),
							Integer.parseInt(((EditText) findViewById(R.id.editPort))
									.getText().toString()), false);
					ObjectOutputStream out = new ObjectOutputStream(server
							.getOutputStream());
					ObjectInputStream is = new ObjectInputStream(server
							.getInputStream());
					User myUser = new User(
							((EditText) findViewById(R.id.editUsername))
									.getText().toString(),
							((EditText) findViewById(R.id.pwPassword))
									.getText().toString());

					// SALT HOLEN
					out.writeObject(new NetworkPacket(myUser, 0, 10,
							new byte[0]));
					byte[] bla = (byte[]) ((NetworkPacket) is.readObject())
							.getData();
					out.flush();
					myUser.setSalt(bla);

					// LOGIN
					socket = new Socket(
							((EditText) findViewById(R.id.editIPorHostname))
									.getText().toString(),
							Integer.parseInt(((EditText) findViewById(R.id.editPort))
									.getText().toString()));
					server = (SSLSocket) factory.createSocket(
							socket,
							((EditText) findViewById(R.id.editIPorHostname))
									.getText().toString(),
							Integer.parseInt(((EditText) findViewById(R.id.editPort))
									.getText().toString()), false);
					out = new ObjectOutputStream(server.getOutputStream());
					is = new ObjectInputStream(server.getInputStream());
					out.writeObject(new NetworkPacket(myUser, 0, 11,
							new byte[0]));
					out.flush();
					boolean blub = (Boolean) ((NetworkPacket) is.readObject())
							.getData();
					out.close();
					is.close();
					if (blub) {*/
						Intent i = new Intent(LoginDataActivity.this,
								EncryptionDetailActivity.class);
						// http://bimbim.in/post/2010/09/27/Android-Passing-object-from-one-activity-to-another.aspx
						Bundle extras = new Bundle();
			            extras.putString("username", ((EditText) findViewById(R.id.editUsername)).getText().toString());
			            extras.putCharArray("userpw", ((EditText) findViewById(R.id.pwPassword)).getText().toString().toCharArray());
			            extras.putString("serverIp", ((EditText) findViewById(R.id.editIPorHostname)).getText().toString());
			            extras.putInt("serverPort", Integer.parseInt(((EditText) findViewById(R.id.editPort)).getText().toString()));
			            i.putExtras(extras);
						startActivity(i);
				/*	}
				} catch (Exception e) {
					Log.e("Connection", e.getMessage());
				}*/
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	/*
	protected AdditionalKeyStoresSSLSocketFactory createAdditionalCertsSSLSocketFactory() {
		try {
			final KeyStore ks = KeyStore.getInstance("BKS");

			// the bks file we generated above
			final InputStream in = getApplicationContext().getResources()
					.openRawResource(R.raw.android);
			try {
				// don't forget to put the password used above in
				// strings.xml/mystore_password
				ks.load(in, "123456".toCharArray());
			} finally {
				in.close();
			}

			return new AdditionalKeyStoresSSLSocketFactory(ks);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}*/

}
/*
final class SSLUtils {

	private SSLUtils() { // non instantiable
	}

	public static String[] getCipherSuitesWhiteList(String[] cipherSuites) {
		List<String> whiteList = new ArrayList<String>();
		List<String> rejected = new ArrayList<String>();
		for (String suite : cipherSuites) {
			String s = suite.toLowerCase();
			if (s.contains("anon") || // reject no anonymous
					s.contains("export") || // reject no export
					s.contains("null") || // reject no encryption
					s.contains("md5") || // reject MD5 (weaknesses)
					s.contains("_des") || // reject DES (key size too small)
					s.contains("krb5") || // reject Kerberos: unlikely to be
											// used
					s.contains("ssl") || // reject ssl (only tls)
					s.contains("empty")) { // not sure what this one is
				rejected.add(suite);
			} else {
				whiteList.add(suite);
			}
		}
		// Log.d(this.getClass().toString(), "Rejected Cipher Suites: {}",
		// rejected);
		return whiteList.toArray(new String[whiteList.size()]);
	}
}*/
